package com.hex.es.component;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.hex.es.bulk.EsOperationEnum;
import com.hex.es.entity.EsInfoDomain;
import com.hex.es.service.AbstractEsBatch;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * es处理路由类
 *
 * @author hex
 * @date 2019/11/04
 */
@Component
@Slf4j
public class EsBatchRouteComponent implements ApplicationContextAware {

    private final Map<EsOperationEnum, AbstractEsBatch> routeMap = Maps.newConcurrentMap();

    /**
     * 路由方法
     * @param esInfoDomains
     * @throws IOException
     */
    public void route(List<EsInfoDomain> esInfoDomains) throws IOException {
        List<EsInfoDomain> collect = esInfoDomains.stream().filter(x -> !x.getOperationEnum().equals(esInfoDomains.get(0).getOperationEnum())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            throw new RuntimeException("es操作集合存在不同操作类型得数据，请检查数据or代码,data："+JSON.toJSON(collect));
        }
        AbstractEsBatch abstractEsBatch = routeMap.get(esInfoDomains.get(0).getOperationEnum());
        abstractEsBatch.handler(esInfoDomains);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String,AbstractEsBatch> serviceMap = applicationContext.getBeansOfType(AbstractEsBatch.class);
        for (AbstractEsBatch abstractEsBatch : serviceMap.values()) {
            routeMap.put(abstractEsBatch.getType(), abstractEsBatch);
        }
    }
}
